<template>
  <div class="add-exam-component-box">
    <div class="add-exam-component">
      <!-- 竞赛信息模块 -->
      <div class="exam-base-info-box">
        <!-- 标题 -->
        <div class="exam-base-title">
          <span class="base-title">{{ title[type] }}</span>
          <span
            class="go-back"
            @click="goBack"
          >返回</span>
        </div>
        <!-- 基本信息 -->
        <div class="exam-base-info">
          <div class="group-box">
            <div class="group-item">
              <div class="item-label required">竞赛名称</div>
              <div>
                <el-input
                  v-if="checkIsPublish()"
                  v-model="formExam.title"
                  style="width:420px"
                  placeholder="请填写竞赛名称"
                  @change="onTitleChange"
                ></el-input>
                <div v-else>{{ formExam.title }}</div>
              </div>
            </div>
          </div>
          <div class="group-box">
            <div class="group-item">
              <div class="item-label required">竞赛周期</div>
              <div>
                <el-date-picker
                  @change="onDateChange"
                  v-if="checkIsPublish()"
                  v-model="formExam.examDate"
                  :disabledDate="disabledDate"
                  type="datetimerange"
                  start-placeholder="竞赛开始时间"
                  end-placeholder="竞赛结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
                <div v-else>{{ formExam.examDate[0] + " 至 " + formExam.examDate[1] }}</div>
              </div>
            </div>
          </div>
          <div class="group-box">
            <div class="group-item">
              <div class="item-label required">是否公开竞赛</div>
              <div>
                <el-switch
                  v-model="formExam.type"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="examId"
                  class="switch"
                />
                <el-button
                  v-if="formExam.type === 0"
                  type="primary"
                  plain
                  @click="editGroupInfo"
                >编辑分组信息</el-button>
              </div>
            </div>
          </div>
          <div class="group-box">
            <div class="group-item">
              <el-button
                v-if="checkIsPublish()"
                class="exam-base-info-button"
                type="primary"
                plain
                @click="saveBaseInfo"
              >保存</el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 添加竞赛题目 -->
      <div class="exam-select-question-box">
        <el-button
          v-if="checkIsPublish()"
          class="exam-add-question"
          :icon="Plus"
          type="text"
          @click="addQuestion()"
        >
          添加题目
        </el-button>
        <!-- 已经添加的题目列表 -->
        <el-table
          height="200px"
          :data="formExam.questionVOList"
          class="question-select-list"
        >
          <el-table-column
            prop="questionId"
            width="180px"
            label="题目id"
          />
          <el-table-column
            prop="title"
            :show-overflow-tooltip="true"
            label="题目标题"
          />
          <el-table-column
            prop="difficulty"
            width="80px"
            label="题目难度"
          >
            <template #default="{ row }">
              <div
                v-if="row.difficulty === 1"
                style="color:#3EC8FF;"
              >简单</div>
              <div
                v-if="row.difficulty === 2"
                style="color:#FE7909;"
              >中等</div>
              <div
                v-if="row.difficulty === 3"
                style="color:#FD4C40;"
              >困难</div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="130px"
          >
            <template #default="{ row }">
              <el-button
                width="60px"
                circle
                type="text"
                @click="onEdit(row.questionId)"
              >
                编辑
              </el-button>
              <el-button
                width="40px"
                v-if="checkIsPublish()"
                type="danger"
                text="danger"
                @click="deleteExamQuestion(formExam.examId, row.questionId, row.title)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 题目配置模块 题目列表勾选加序号 -->
      <div>
        <el-dialog
          v-model="dialogVisible"
          :before-close="handleClose"
        >
          <div class="exam-list-box">
            <!-- 搜索 -->
            <div class="exam-list-title required">选择竞赛题目</div>
            <el-form inline="true">
              <el-form-item label="题目难度">
                <selector
                  v-model="queryQuestionParams.difficulty"
                  style="width: 120px;"
                ></selector>
              </el-form-item>
              <el-form-item label="题目名称">
                <el-input
                  v-model.trim="queryQuestionParams.title"
                  placeholder="请您输入要搜索的题目标题"
                  @keydown.enter="onSearch"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  @click="onSearch"
                  plain
                >搜索</el-button>
                <el-button
                  @click="onReset"
                  plain
                  type="info"
                >重置</el-button>
              </el-form-item>

            </el-form>
            <!-- 未添加的题目列表 -->
            <el-table
              :data="questionList"
              @select="handleRowSelect"
              @select-all="handleRowSelect"
            >
              <el-table-column type="selection"></el-table-column>
              <el-table-column
                prop="questionId"
                label="题目id"
              />
              <el-table-column
                prop="title"
                label="题目标题"
              />
              <el-table-column
                prop="difficulty"
                label="题目难度"
              >
                <template #default="{ row }">
                  <div
                    v-if="row.difficulty === 1"
                    style="color:#3EC8FF;"
                  >简单</div>
                  <div
                    v-if="row.difficulty === 2"
                    style="color:#FE7909;"
                  >中等</div>
                  <div
                    v-if="row.difficulty === 3"
                    style="color:#FD4C40;"
                  >困难</div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <div class="exam-question-list-button">
              <el-pagination
                background
                size="small"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalNum"
                v-model:current-page="queryQuestionParams.pageNum"
                v-model:page-size="queryQuestionParams.pageSize"
                :page-sizes="[1, 5, 10, 15, 20]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
              <el-button
                class="question-select-submit"
                type="primary"
                plain
                @click="submitSelectQuestion"
              >提交</el-button>
            </div>
          </div>
        </el-dialog>
      </div>

      <!-- 添加用户组 -->
      <div>
        <el-dialog
          v-model="dialogUserGroupVisible"
          :before-close="handleClose"
        >
          <div class="exam-list-box">
            <!-- 搜索 -->
            <div class="exam-list-title required">选择用户组</div>
            <!-- 表单 -->
            <el-form inline="true">
              <el-form-item label="用户组昵称">
                <el-input
                  v-model="userGroupQueryParams.nickName"
                  placeholder="请您输入要搜索的用户组昵称"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  @click="onUserGroupSearch"
                  plain
                >搜索</el-button>
                <el-button
                  @click="onUserGroupReset"
                  plain
                  type="info"
                >重置</el-button>
              </el-form-item>
            </el-form>
            <!-- 查看用户组列表 -->
            <el-table
              :data="userGroupList"
              ref="userGroupTableRef"
              @select="handleUserGroupRowSelect"
              @select-all="handleUserGroupRowSelect"
              row-key="userGroupId"
            >
              <el-table-column
                type="selection"
                :reserve-selection="true"
              ></el-table-column>
              <el-table-column
                prop="userGroupId"
                label="用户组Id"
              />
              <el-table-column
                prop="nickName"
                label="用户组昵称"
              />
              <el-table-column
                prop="introduce"
                label="用户组简介"
              />
            </el-table>
            <!-- 分页区域 -->
            <div class="exam-question-list-button">
              <el-pagination
                background
                size="small"
                layout="total, sizes, prev, pager, next, jumper"
                :total="userGroupTotal"
                v-model:current-page="queryQuestionParams.pageNum"
                v-model:page-size="queryQuestionParams.pageSize"
                :page-sizes="[1, 5, 10, 15, 20]"
                @size-change="handleUserGroupSizeChange"
                @current-change="handleUserGroupCurrentChange"
              />
              <el-button
                class="question-select-submit"
                type="primary"
                plain
                @click="submitSelectUserGroup"
              >提交</el-button>
            </div>
          </div>
        </el-dialog>
      </div>

      <!-- 提交任务区域 -->
      <div
        class="submit-box absolute"
        v-if="checkIsPublish()"
      >
        <el-button
          type="info"
          plain
          @click="goBack"
        >取消</el-button>
        <el-button
          type="primary"
          plain
          @click="publishExam"
        >发布竞赛</el-button>
      </div>
    </div>
  </div>
  <QuestionDrawer
    ref="questionDrawerRef"
    @success="onSuccess"
  />
</template>

<script setup>
  import { OPERATION_TYPE, PAGE_VALUE } from "@/constants/CRUDConstants"
  import { addExamService, questionAddService, getExamDetailService, editExamService, deleteExamQuestionByIdService, publishExamService, getExamGroupIdByExamIdService } from "@/apis/exam"
  import { getQuestionListService } from "@/apis/questionApi"
  import Selector from "@/components/QuestionSelector.vue"
  import router from '@/router'
  import { nextTick, reactive, ref } from "vue"
  import { Plus } from '@element-plus/icons-vue'
  import { useRoute } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { SPLIT } from '@/constants/constants'
  import { STATUS_TYPE } from '@/constants/exam'
  import { getUserGroupListService, updateExamUserGroupService } from '@/apis/cuserGroup'

  const title = {
    [OPERATION_TYPE.EDIT]: '编辑竞赛',
    [OPERATION_TYPE.ADD]: '添加竞赛',
    [OPERATION_TYPE.DETAIL]: '查看竞赛'
  }

  let { examId, type } = useRoute().query
  const formExam = reactive({
    examId: examId,
    title: '',
    examDate: '',
    questionVOList: [],
    status: '',
    type: 0
  })


  function checkIsPublish() {
    return !formExam.status || formExam.status === STATUS_TYPE.UN_PUBLISHED
  }


  // 返回
  function goBack() {
    router.go(-1)
  }

  function checkBaseInfo() {
    if (!formExam.title) {
      ElMessage.warning('请输入竞赛标题')
      return false
    } else if (!formExam.examDate) {
      ElMessage.warning('请选择竞赛时间')
      return false
    } else {
      return true
    }
  }

  const isSaveUpdate = ref(true)

  function onDateChange(value) {
    isSaveUpdate.value = false
  }

  function onTitleChange(value) {
    isSaveUpdate.value = false
  }

  async function saveBaseInfo() {
    console.log(checkBaseInfo());
    if (!checkBaseInfo()) {
      return
    }
    const fd = new FormData()
    for (let key in formExam) {
      if (key === 'examDate') {
        fd.append('startTime', formExam.examDate[0]);
        fd.append('endTime', formExam.examDate[1]);
      } else if (key !== 'startTime' && key !== 'endTime') {
        fd.append(key, formExam[key])
      }
    }
    if (type === OPERATION_TYPE.EDIT) {
      await editExamService(fd)
    } else if (type === OPERATION_TYPE.ADD) {
      const { data } = await addExamService(fd)
      formExam.examId = data
      examId = data
      type = OPERATION_TYPE.EDIT // 添加成功后，修改为编辑状态 因为修改一下名字然后保存 这样会出现一次性创建多个竞赛的bug
    } else if (type === OPERATION_TYPE.DETAIL) {
      await editExamService(fd)
      return
    }
    ElMessage.success('基本信息保存成功')
    isSaveUpdate.value = true
  }

  /** 编辑用户组相关内容 **/
  async function editGroupInfo() {
    if (!examId) {
      ElMessage.warning('请先保存竞赛的基本信息')
      return
    }
    dialogUserGroupVisible.value = true
    // 获取已经添加的用户组列表
    const { data } = await getExamGroupIdByExamIdService(examId)
    userGroupIdList.value = data
    console.log(data);

    // 获取可以选择的用户组列表
    getUserGroupList()
  }

  const dialogUserGroupVisible = ref(false)
  const userGroupList = ref([]) // 已经存在的用户组列表
  const userGroupIdList = ref([]) // 选中的用户组Id
  const userGroupTableRef = ref(null)

  const userGroupTotal = ref(0)

  const userGroupQueryParams = reactive({
    pageNum: PAGE_VALUE.PAGE_NUM,
    pageSize: PAGE_VALUE.PAGE_SIZE,
    nickName: '',
  })

  async function submitSelectUserGroup() {
    const data = {
      examId,
      userGroupIds: userGroupIdList.value,
    }
    await updateExamUserGroupService(data)
    ElMessage.success('用户组添加成功')
    dialogUserGroupVisible.value = false
  }

  async function getUserGroupList() {
    const { total, rows } = await getUserGroupListService(userGroupQueryParams)
    userGroupTotal.value = total
    userGroupList.value = rows
    nextTick(() => {
      rows.forEach(item => {
        userGroupTableRef.value.toggleRowSelection(item,
          userGroupIdList.value.includes(item.userGroupId)
        )
      })
    })
  }

  function handleUserGroupRowSelect(selection) {
    userGroupIdList.value = []
    selection.forEach(item => {
      if (userGroupIdList.value.indexOf(item.userGroupId) === -1) {
        userGroupIdList.value.push(item.userGroupId)
      }
    })
  }

  function onUserGroupReset() {
    userGroupQueryParams.nickName = ''
    userGroupQueryParams.pageNum = PAGE_VALUE.PAGE_NUM
    userGroupQueryParams.pageSize = PAGE_VALUE.PAGE_SIZE
    getUserGroupList()
  }

  function onUserGroupSearch() {
    getUserGroupList()
  }

  function handleUserGroupSizeChange(newSize) {
    userGroupQueryParams.pageNum = PAGE_VALUE.PAGE_NUM
    userGroupQueryParams.pageSize = newSize
    getUserGroupList()
  }

  function handleUserGroupCurrentChange(newPage) {
    userGroupQueryParams.pageNum = newPage
    getUserGroupList()
  }


  /** 添加题目列表相关内容 **/
  function addQuestion() {
    if (!formExam.examId) {
      ElMessage.warning('请先保存竞赛的基本信息')
      return
    }
    dialogVisible.value = true
    // 获取题目列表
    getQuestionList()
  }

  const queryQuestionParams = reactive({
    pageNum: PAGE_VALUE.PAGE_NUM,
    pageSize: PAGE_VALUE.PAGE_SIZE,
    title: "",
    difficulty: "",
    excludeQuestionIdsStr: ""
  })

  const totalNum = ref(0) // 总个数
  const questionList = ref([])
  const dialogVisible = ref(false)
  const questionIds = ref([])

  // 清空题目
  function clearDialog() {
    onReset()
    questionIds.value.length = 0
  }

  async function handleClose(done) {
    // await ElMessageBox.confirm('确定要取消编辑吗？', '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })
    done()
    // // dialogVisible.value = false
    // clearDialog()
  }
  function handleRowSelect(selection) {
    questionIds.value = []
    selection.forEach(item => {
      questionIds.value.push(item.questionId)
    })
  }

  async function submitSelectQuestion() {
    if (!questionIds.value || questionIds.value.length === 0) {
      ElMessage.warning('请选择题目')
      return
    }
    await questionAddService(formExam.examId, questionIds.value)
    ElMessage.success('添加题目成功')
    dialogVisible.value = false
    getExamDetail()
  }

  async function getQuestionList() {
    queryQuestionParams.excludeQuestionIdsStr = formExam.questionVOList.map(item => item.questionId).join(SPLIT.SEM)
    const { rows, total } = await getQuestionListService(queryQuestionParams)
    questionList.value = rows
    totalNum.value = total
  }

  let oldSize = queryQuestionParams.pageSize;
  function handleCurrentChange(newPage) {
    getQuestionList()
  }

  function handleSizeChange(newSize) {
    // 从客户角度出发 由多变少 那么就去当前页面的第一个值的页面 反之亦然
    const curFirstNum = (queryQuestionParams.pageNum - 1) * oldSize + 1 // 当前页面的第一个值在总数中的位置
    queryQuestionParams.pageNum = Math.ceil(curFirstNum / newSize)
    oldSize = newSize
    getQuestionList()
  }

  function onSearch() {
    queryQuestionParams.pageNum = 1
    getQuestionList()
  }

  function onReset() {
    queryQuestionParams.pageNum = PAGE_VALUE.PAGE_NUM
    queryQuestionParams.pageSize = PAGE_VALUE.PAGE_SIZE
    queryQuestionParams.title = ""
    queryQuestionParams.difficulty = ""
    getQuestionList()
  }

  async function getExamDetail() {
    if (!formExam.examId) {
      return
    }
    // formExam.questionVOList = []
    const { data } = await getExamDetailService(formExam.examId)
    Object.assign(formExam, data)
    formExam.examDate = [data.startTime, data.endTime]
  }
  getExamDetail()

  async function deleteExamQuestion(examId, questionId, title) {
    await ElMessageBox.confirm(`确定要删除题目 ${title} 吗？`, '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' })

    await deleteExamQuestionByIdService(examId, questionId)
    // 可以直接获取 但是也可以通过删除数组中的内容来减少请求次数
    // getExamDetail()
    formExam.questionVOList = formExam.questionVOList.filter(item => item.questionId !== questionId)
    ElMessage.success('题目删除成功')
  }

  async function publishExam() {
    console.log(isSaveUpdate.value);

    if (!checkBaseInfo()) {
      return
    } else if (!isSaveUpdate.value) {
      ElMessage.warning('请先保存竞赛的基本信息')
      return
    }
    await publishExamService(formExam.examId)
    ElMessage.success('竞赛发布成功')
    router.push('/oj/layout/exam')
  }

  /**  抽屉相关内容  **/
  const questionDrawerRef = ref(null)
  function onEdit(questionId) {
    questionDrawerRef.value.open(questionId)
  }
  function onSuccess(type) {
    getExamDetail()
  }
</script>

<style lang="scss" scoped>
  .add-exam-component-box {
    height: 100%;
    overflow: hidden;
    position: relative;
  }

  .exam-list-box {
    background: #fff;
    padding: 20px 24px;

    .question-select-submit {
      margin-left: 0;
      margin-top: 20px;
      width: 100%;
    }

    .exam-list-title {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
      position: relative;
      padding: 15px 20px;
      padding-top: 0;

      &.required::before {
        position: absolute;
        content: '*';
        font-size: 20px;
        color: red;
        left: 10px;
      }
    }
  }

  .add-exam-component {
    width: 100%;
    background: #fff;
    padding-bottom: 120px;
    overflow-y: auto;
    box-sizing: border-box;
    height: calc(100vh - 50px);
    margin-top: -10px;

    .exam-select-question-box {

      background: #fff;
      border-bottom: 1px solid #fff;
      border-radius: 2px;
      width: 100%;

      .exam-add-question {
        font-size: 14px;
        float: right;
        margin: 10px 20px 5px 0;
      }

      .question-select-list {
        margin: 0 0 20px 0;
        height: 200px;
      }
    }

    .exam-base-info-box {
      background: #fff;
      border-bottom: 1px solid #fff;
      border-radius: 2px;
      margin-bottom: 10px;
      width: 100%;
      box-sizing: border-box;

      .exam-base-title {
        width: 100%;
        box-sizing: border-box;
        height: 52px;
        border-bottom: 1px solid #e9e9e9;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .base-title {
          font-size: 16px;
          font-weight: 500;
          color: #333333;
        }

        .go-back {
          color: #999;
          cursor: pointer;
        }
      }

      .exam-base-info {
        box-sizing: border-box;
        border-bottom: 1px solid #e9e9e9;
      }

      .mesage-list-content {
        box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);
        background-color: rgba(255, 255, 255, 1);
        border-radius: 10px;
        width: 1200px;
        margin-top: 20px;
      }
    }

    .group-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: calc(100% - 64px);
      margin: 24px 0;

      .group-item {
        display: flex;
        align-items: center;
        width: 100%;

        .exam-base-info-button {
          margin-left: 104px;
          width: 420px;
        }

        .item-label {
          font-size: 14px;
          font-weight: 400;
          width: 94px;
          text-align: left;
          color: rgba(0, 0, 0, 0.85);
          position: relative;
          padding-left: 10px;

          &.required::before {
            position: absolute;
            content: '*';
            font-size: 20px;
            color: red;
            left: 0px;
            top: -2px;
          }
        }
      }
    }

    .submit-box {
      display: flex;
      align-items: center;
      justify-content: center;
      background: transparent;

      &.absolute {
        position: absolute;
        width: calc(100% - 48px);
        bottom: 0;
        background: #fff;
        z-index: 999;
      }
    }
  }

  .switch {
    margin-right: 10px;

  }
</style>

<style>
  .w-e-text-container {
    min-height: 142px;
  }
</style>